﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Msg;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    /// <summary>
    /// 诉请要素关系配置（XPath）
    /// </summary>
    public partial class frmZhengJuConfig : BaseForm
    {
        /// <summary>
        /// 情形情节业务逻辑类
        /// </summary>
        readonly CaseCauseBLL _caseCauseBll = new CaseCauseBLL();

        SYS_CaseCauseElement_EvidRelBLL bll = new SYS_CaseCauseElement_EvidRelBLL();

        SYS_Argument_ElementRelBLL bllFocus = new SYS_Argument_ElementRelBLL();

        /// <summary>
        /// 页面标签与诉情种类关系列表
        /// </summary>
        public IList<SYS_CaseCauseElement_EvidRel> SysCaseCauseElement { get; set; }

        /// <summary>
        /// 要素争议焦点类
        /// </summary>
        public IList<SYS_Argument_ElementRel> SysArgumentElementRel { get; set; }

        /// <summary>
        /// 案由节点
        /// </summary>
        public string CcId { get; set; }

        /// <summary>
        /// 配置节点
        /// </summary>
        public string CcConfigId { get; set; }

        /// <summary>
        /// CdID
        /// </summary>
        public string CdID { get; set; }

        /// <summary>
        /// CdID
        /// </summary>
        public string CCName { get; set; }

        /// <summary>
        /// 0:证据要素 1:争议焦点
        /// </summary>
        public Int32 TagNum { get; set; }


        /// <summary>
        /// 生成ID逻辑类
        /// </summary>
        readonly NewIDBLL _newIdbll = new NewIDBLL();
        IList<SYS_CaseCauseElement_EvidRel> SysCaseCauseElementNew = new List<SYS_CaseCauseElement_EvidRel>();
        IList<SYS_Argument_ElementRel> SysArgumentFocusNew = new List<SYS_Argument_ElementRel>();

        DataTable dt = new DataTable();

        public frmZhengJuConfig(int tag)
        {
            InitializeComponent();
            TagNum = tag;
            SysCaseCauseElement = new List<SYS_CaseCauseElement_EvidRel>();
            SysArgumentElementRel = new List<SYS_Argument_ElementRel>();
        }

        /// <summary>
        /// 界面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSuitTypeRel_Load(object sender, EventArgs e)
        {
            dt = _caseCauseBll.GetCriminalNodes(CcId);
            if (dt != null && dt.Rows.Count > 0 && dt.Select(" CC_ID='" + CcId + "' ").Length > 0)
            {
                DataRow dr = dt.Select(" CC_ID='" + CcId + "' ")[0];
                var tn = new TreeNode(dr["CC_Name"].ToString()) { Tag = dr["CC_ID"].ToString() };
                treeView1.Nodes.Add(tn);
                if (dt.Select(" CC_ParentID='" + tn.Tag + "' ").Length > 0)
                {
                    tn.Nodes.Add(new TreeNode());
                }
            }
            if (TagNum == 0)
            {
                dgvZhengJu.Dock = DockStyle.Fill;
                dgvZhengJu.AutoGenerateColumns = false;
                dgvFocus.Visible = false;
            }
            else if (TagNum == 1)
            {
                dgvFocus.Dock = DockStyle.Fill;
                dgvFocus.AutoGenerateColumns = false;
                dgvZhengJu.Visible = false;
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            if (TagNum == 0)
            {
                dgvZhengJu.DataSource = SysCaseCauseElement != null && SysCaseCauseElement.Any() ? SysCaseCauseElement.ToList() : null;
            }
            else if (TagNum == 1)
            {
                dgvFocus.DataSource = SysArgumentElementRel != null && SysArgumentElementRel.Any() ? SysArgumentElementRel.ToList() : null;
            }
        }

        #region 节点效果
        /// <summary>
        /// 节点展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            var selectNode = e.Node;
            selectNode.Nodes.Clear();

            if (dt.Select(" CC_ParentID='" + e.Node.Tag + "' ", " CC_SerialNumb asc ").Length > 0)
            {
                DataRow[] drs = dt.Select(" CC_ParentID='" + e.Node.Tag + "' ", "  CC_SerialNumb  asc ");
                foreach (var dr in drs)
                {
                    var childNode = new TreeNode(dr["CC_Name"].ToString()) { Tag = dr["CC_ID"].ToString() };
                    if (dt.Select(" CC_ParentID='" + childNode.Tag + "' ").Length > 0)
                    {
                        childNode.Nodes.Add(new TreeNode());
                    }
                    selectNode.Nodes.Add(childNode);
                }
            }
        }

        /// <summary>
        /// 节点选择之后，考虑到性能和后期生成XPath的便利，在每次选后都存储数据到内存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Checked)
            {
                if (e.Node.Text.Equals("属性"))
                {
                    MsgBox.Warn("不能选择属性做为节点");
                    return;
                }
                var text = "";
                var tn = e.Node;
                var selectCcid = e.Node.Tag.ToString();
                var labelType = string.Empty;

                do
                {
                    //当前节点值为属性，则排除属性，直接找上级节点
                    if (tn.Text.Equals(@"属性"))
                    {
                        tn = tn.Parent;
                    }
                    if (tn.Parent != null && tn.Parent.Text.Equals(@"属性"))
                    {
                        text = ("/@" + tn.Text) + text;
                    }
                    else
                    {
                        //拼接XPath路径
                        text = ("/" + tn.Text) + text;
                    }
                    if (tn.Parent != null)
                    {
                        tn = tn.Parent;
                    }
                    else
                    {
                        break;
                    }

                } while (true);

                if (TagNum == 0)
                {
                    var model = new SYS_CaseCauseElement_EvidRel()
                    {
                        ccID = e.Node.Tag.ToString(),
                        CD_ID = CdID,
                        XmlPath = text,
                        CER_ID = _newIdbll.JudgeDoc_CreateID("SYS_CaseCauseElement_EvidRel")
                    };
                    if (!SysCaseCauseElement.Contains(model))
                    {
                        SysCaseCauseElement.Add(model);
                    }
                }
                else if (TagNum == 1)
                {
                    var model = new SYS_Argument_ElementRel()
                    {
                        AER_ID = _newIdbll.JudgeDoc_CreateID("SYS_Argument_ElementRel"),
                        CC_ID = CcConfigId,
                        XmlPath = text
                    };
                    if (!SysArgumentElementRel.Contains(model))
                    {
                        SysArgumentElementRel.Add(model);
                    }
                }
            }
            else
            {
                if (TagNum == 0)
                {
                    if (SysCaseCauseElement != null && SysCaseCauseElement.Any(x => x.ccID == e.Node.Tag.ToString()))
                    {
                        var deleteModel = SysCaseCauseElement.FirstOrDefault(x => x.ccID == e.Node.Tag.ToString());
                        SysCaseCauseElement.Remove(deleteModel);
                    }
                }
                else if (TagNum == 1)
                {
                    if (SysArgumentElementRel != null && SysArgumentElementRel.Any(x => x.CC_ID == e.Node.Tag.ToString()))
                    {
                        var deleteModel = SysArgumentElementRel.FirstOrDefault(x => x.CC_ID == e.Node.Tag.ToString());
                        SysArgumentElementRel.Remove(deleteModel);
                    }
                }
            }
        }
        #endregion

        #region 生成XPath
        /// <summary>
        /// 生成XPath
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnXPath_Click(object sender, EventArgs e)
        {
            BindData();
        }
        #endregion


        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (TagNum == 0)
                {
                    if (SysCaseCauseElement != null && SysCaseCauseElement.Any())
                    {
                        StringBuilder sb = new StringBuilder();
                        var dtRel = bll.GetSysCaseCauseElementData(CdID, CCName);
                        if (dtRel != null && dtRel.Rows.Count > 0)
                        {
                            for (int i = 0; i < SysCaseCauseElement.Count; i++)
                            {
                                if (dtRel.Select(" XmlPath='" + SysCaseCauseElement[i].XmlPath + "' ").Length > 0)
                                {
                                    sb.Append(SysCaseCauseElement[i].XmlPath + "\r\n");
                                }
                                else
                                {
                                    SysCaseCauseElementNew.Add(SysCaseCauseElement[i]);
                                }
                            }
                        }
                        else
                        {
                            SysCaseCauseElementNew = SysCaseCauseElement;
                        }
                        if (SysCaseCauseElementNew.Count > 0)
                        {
                            if (bll.BatchAdd(SysCaseCauseElementNew))
                            {
                                if (!string.IsNullOrEmpty(sb.ToString()))
                                {
                                    sb.Insert(0, " 保存成功但在数据库中存在如下配置XPATH:\r\n");
                                    MessageBox.Show(sb.ToString());
                                }
                                else
                                {
                                    MsgBox.OK("保存成功");
                                }
                                this.DialogResult = DialogResult.Yes;
                                return;
                            }
                        }
                        else if (!string.IsNullOrEmpty(sb.ToString()))
                        {
                            sb.Insert(0, " 在数据库中存在如下配置XPATH:\r\n");
                            MessageBox.Show(sb.ToString());
                            return;
                        }

                    }
                    else
                    {
                        MsgBox.Warn("没有任何项需要添加");
                    }
                }
                else if (TagNum == 1)
                {
                    if (SysArgumentElementRel != null && SysArgumentElementRel.Any())
                    {
                        StringBuilder sb = new StringBuilder();
                        var dtFocus = bllFocus.GetSysArgumentElementRelDatas();
                        if (dtFocus != null && dtFocus.Rows.Count > 0)
                        {
                            for (int i = 0; i < SysArgumentElementRel.Count; i++)
                            {
                                if (dtFocus.Select(" XmlPath='" + SysArgumentElementRel[i].XmlPath + "' ").Length > 0)
                                {
                                    sb.Append(SysArgumentElementRel[i].XmlPath + "\r\n");
                                }
                                else
                                {
                                    SysArgumentFocusNew.Add(SysArgumentElementRel[i]);
                                }
                            }
                        }
                        else
                        {
                            SysArgumentFocusNew = SysArgumentElementRel;
                        }
                        if (SysArgumentFocusNew.Count > 0)
                        {
                            if (bllFocus.BatchAdd(SysArgumentFocusNew))
                            {
                                if (!string.IsNullOrEmpty(sb.ToString()))
                                {
                                    sb.Insert(0, " 保存成功但在数据库中存在如下配置XPATH:\r\n");
                                    MessageBox.Show(sb.ToString());
                                }
                                else
                                {
                                    MsgBox.OK("保存成功");
                                }
                                this.DialogResult = DialogResult.Yes;
                                return;
                            }
                        }
                        else if (!string.IsNullOrEmpty(sb.ToString()))
                        {
                            sb.Insert(0, " 在数据库中存在如下配置XPATH:\r\n");
                            MessageBox.Show(sb.ToString());
                            return;
                        }

                    }
                    else
                    {
                        MsgBox.Warn("没有任何项需要添加");
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.Err("保存失败" + ex.Message);
            }
        }



        #endregion

    }


}
